package com.demo.permission.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.permission.enums.RoleType;
import com.demo.permission.mapper.PermissionMapper;
import com.demo.permission.entity.Roles;
import com.demo.permission.entity.UserRoles;
import com.demo.permission.service.IPermissionService;
import com.demo.permission.service.IRolesService;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.transaction.annotation.ShardingSphereTransactionType;
import org.apache.shardingsphere.transaction.core.TransactionType;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hxt
 * @since 2025-06-17
 */
@Service
@RequiredArgsConstructor
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, UserRoles> implements IPermissionService {

    private final IRolesService rolesService;

    /**
     * 绑定默认角色
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @ShardingSphereTransactionType(value = TransactionType.BASE)
    public void bindDefaultRole(Long userId) {
        UserRoles userRoles = new UserRoles();
        userRoles.setUserId(userId);
        userRoles.setRoleId(RoleType.USER.getValue());
        save(userRoles);
    }

    /**
     * 获取用户角色码
     * @param userId
     * @return
     */
    public String getUserRoleCode(Long userId) {
        UserRoles userRoles = lambdaQuery()
                .eq(UserRoles::getUserId, userId)
                .one();
        if (userRoles == null) {
            return null;
        }
        return rolesService.getById(userRoles.getRoleId()).getRoleCode();
    }

    /**
     * 升级为管理员
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @ShardingSphereTransactionType(value = TransactionType.BASE)
    public void upgradeToAdmin(Long userId) {
        UserRoles userRoles = lambdaQuery()
                .eq(UserRoles::getUserId, userId)
                .one();
        if (userRoles == null || !Objects.equals(userRoles.getRoleId(), RoleType.USER.getValue())){
            return;
        }
        userRoles.setRoleId(RoleType.ADMIN.getValue());
        updateById(userRoles);
    }

    /**
     * 降级为普通用户
     * @param userId
     */
    @Transactional(rollbackFor = Exception.class)
    @ShardingSphereTransactionType(value = TransactionType.BASE)
    public void downgradeToUser(Long userId) {
        UserRoles userRoles = lambdaQuery()
                .eq(UserRoles::getUserId, userId)
                .one();
        if (userRoles == null || !Objects.equals(userRoles.getRoleId(), RoleType.ADMIN.getValue())){
            return;
        }
        userRoles.setRoleId(RoleType.USER.getValue());
        updateById(userRoles);
    }

    /**
     * 根据角色码获取用户id
     * @param roleCodes
     * @return
     */
    public List<Long> getUserIdByRoleCodes(List<String> roleCodes) {
        // 获取角色id
        List<Integer> list = rolesService.lambdaQuery()
                .select(Roles::getRoleId)
                .in(Roles::getRoleCode, roleCodes)
                .list()
                .stream().map(Roles::getRoleId).collect(Collectors.toList());
        // 获取用户id
        return lambdaQuery()
                .select(UserRoles::getUserId)
                .in(UserRoles::getRoleId, list)
                .list()
                .stream().map(UserRoles::getUserId).collect(Collectors.toList());
    }
}
